package org.chengyi.model_shop.service.impl;

import jakarta.servlet.http.HttpServletRequest;
import org.chengyi.model_shop.entity.User;
import org.chengyi.model_shop.mapper.LoginMapper;
import org.chengyi.model_shop.service.LoginService;
import org.chengyi.model_shop.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public Map<String, Object> login(String username, String password, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        // 参数验证
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            result.put("success", false);
            result.put("message", "用户名和密码不能为空");
            return result;
        }

        // 查找用户
        User user = loginMapper.findByUsername(username);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户名不存在");
            return result;
        }

        // 密码加密比对
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encryptedPassword.equals(user.getPassword())) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }
        // 保存用户ID到session中 然后在拦截器中获取 将用户ID保存到ThreadLocal中
        request.getSession().setAttribute("userId", user.getId());
        // 登录成功，返回用户信息
        result.put("success", true);
        result.put("message", "登录成功");
        result.put("user", user);
        return result;
    }

    @Override
    public Map<String, Object> register(String username, String email, String password, String confirmPassword) {
        Map<String, Object> result = new HashMap<>();

        // 参数验证
        if (!StringUtils.hasText(username) || !StringUtils.hasText(email) ||
                !StringUtils.hasText(password) || !StringUtils.hasText(confirmPassword)) {
            result.put("success", false);
            result.put("message", "所有字段不能为空");
            return result;
        }

        if (!password.equals(confirmPassword)) {
            result.put("success", false);
            result.put("message", "两次输入的密码不一致");
            return result;
        }

        if (password.length() < 6) {
            result.put("success", false);
            result.put("message", "密码长度不能少于6位");
            return result;
        }

        // 检查用户名和邮箱是否已存在
        if (loginMapper.findByUsername(username) != null) {
            result.put("success", false);
            result.put("message", "用户名已存在");
            return result;
        }

        if (loginMapper.findByEmail(email) != null) {
            result.put("success", false);
            result.put("message", "邮箱已存在");
            return result;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setRole(0); // 默认普通用户
        user.setCreatedAt(new Date());

        // 执行注册
        try {
            int affectedRows = loginMapper.register(user);
            if (affectedRows > 0) {
                result.put("success", true);
                result.put("message", "注册成功");
                result.put("user", user); // 返回用户信息
            } else {
                result.put("success", false);
                result.put("message", "注册失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        }

        return result;
    }

}
